﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using Grain.Crm.ExcelExtractor.InputDescription;
using Grain.Crm.ExcelImporter;

namespace Grain.Crm.ExcelExtractor
{
    public class XlsValueRetriever
    {
        /// <summary>
        /// Gets the value from xlt-parsed collection. 
        /// If number is to retrieve, it parses it according to current culture and returns it as culture-invariant string.
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public static string GetValueByDescription(EnumerableRowCollection<DataRow> collection, ValueDescription description)
        {
            var value = collection.GetValue(description.Row, description.Column);

            if(description.IsNumber)
            {
                double number;
                var isParsed = double.TryParse(value.Replace(" ", ""), NumberStyles.Number, new CultureInfo(ValueDescription.SheetCulture), out number);
                
                if(isParsed)
                    return number.ToString(new CultureInfo(""));
                else
                    throw new FormatException(
                        "The value couldn't be parsed as number. XlsField: " 
                        + description.XlsDescription + ". Value: '" + value 
                        + "'. Culture used: " + ValueDescription.SheetCulture);
            }

            return value;
        }
    }
}
